package com.kris;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * 用于过滤指定日期范围内的考勤记录
 *
 * @author Kris
 */
class DateFilter {

    private final Date beginDate;
    private final Date endDate;
    private final int dateColumnIndex;

    DateFilter(Date beginDate, Date endDate, int dateColumnIndex) {
        if (beginDate != null) {
            // 设置为一天的最开始
            Calendar b = Calendar.getInstance();
            b.setTime(beginDate);
            b.set(Calendar.HOUR_OF_DAY, 0);
            b.set(Calendar.MINUTE, 0);
            b.set(Calendar.SECOND, 0);
            this.beginDate = b.getTime();
        } else {
            this.beginDate = null;
        }

        if (endDate != null) {
            // 设置为一天的最后一秒
            Calendar e = Calendar.getInstance();
            e.setTime(endDate);
            e.set(Calendar.HOUR_OF_DAY, 23);
            e.set(Calendar.MINUTE, 59);
            e.set(Calendar.SECOND, 59);
            this.endDate = e.getTime();
        } else {
            this.endDate = null;
        }
        this.dateColumnIndex = dateColumnIndex;
    }

    int getColumnIndex() {
        return this.dateColumnIndex;
    }

    boolean match(String text) throws ParseException {
        // 如果文本为空，这认为是不匹配的数据
        if (text == null || "".equals(text.trim())) {
            return false;
        }

        if (this.beginDate == null && this.endDate == null) {
            // 认为没有过滤
            return true;
        }

        Date date = DateUtil.convert(text, "yyyy/MM/dd HH:mm:ss");

        // 判断指定日期是否在范围内
        if (this.beginDate != null && this.endDate != null
                && this.beginDate.before(date) && this.endDate.after(date)) {
            return true;
        } else if (this.beginDate != null && this.endDate == null) {
            if (this.beginDate.before(date)) {
                return true;
            }
        } else if (this.beginDate == null && this.endDate != null) {
            if (this.endDate.after(date)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws ParseException {
        DateFilter x = new DateFilter(new Date(), new Date(), 1);
        System.out.println(x.match("2016/11/10 00:00:00"));
    }

}
